package com.study.springsecurity.security.handler;

import com.study.springsecurity.constant.CommonConstant;
import com.study.springsecurity.constant.ErrorCode;
import com.study.springsecurity.pojo.Result;
import com.study.springsecurity.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录认证失败的处理
 *
 * @Author YL
 * @Create 2024/4/3 17:36
 * @Version 1.0
 */
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.error("MyAuthenticationFailureHandler onAuthenticationFailure，原因：" + exception.getMessage());
        if (exception instanceof BadCredentialsException) {
            Result result = new Result();
            result.setCode(ErrorCode.E000002.code()).setMessage(ErrorCode.E000002.msg());
            ResponseUtil.writeJsonUtf8(response, HttpStatus.OK, result);
        } else {
            response.sendRedirect(request.getContextPath() + CommonConstant.PageUrl.LOGIN_PAGE);
        }
    }
}
